/*
 * hs_parser.cpp
 *
 *  Created on: 2012-6-1
 *      Author: li.zhaoping
 */
#include<stdlib.h>
#include <stdio.h>
#include <string.h>
#include <string>

#include "pcre_wrapper.h"

#define OVECCOUNT 30    /* should be a multiple of 3 */

int main(int argc, char **argv) {

	//prepare express
	char *pattern_td = "<div id=\"message.*?</div>";
	int *re_td = pcre_new_express(pattern_td);
	if (re_td == 0) {
		printf("PCRE compilation NULL\n");
		return 1;
	}
	char *pattern_a = "<img.*?/>";
	int *re_a = pcre_new_express(pattern_a);
	if (re_a == 0) {
		printf("PCRE compilation NULL\n");
		return 1;
	}

	char *pattern_url = "src=\".*?\"";
	int *re_url = pcre_new_express(pattern_url);
	if (re_url == 0) {
		printf("PCRE compilation NULL\n");
		return 1;
	}

	//prepare data
	std::string bufs = "";
	int line = 0;
	char lbuf[256];
	while (fgets(lbuf, sizeof(lbuf), stdin)) {
		lbuf[strlen(lbuf) - 1] = 0;
		bufs += lbuf;
	}
	char *data = (char*) bufs.c_str();
	int dataSize = (int) strlen(data);

	//prepare do loop
	int ovector[OVECCOUNT];
	memset(ovector, -1, sizeof(ovector));
	int offset = 0, retStart = 0, retLen = 0;
	int imatch = 0;
	for (;;) {
		// do parser td
		int rt = pcre_exc_express(re_td, data, dataSize, offset, &retStart,
				&retLen);
		if (rt == -1) {
			//			printf("\033[1;31m%s\033[0m]\n", "Not match 0");
			break;
		}
		else {
			char *substring_start = data + retStart;
			//			printf("[%3d]Match==>\033[1;31m%.*s\033[0m\n", imatch, retLen,
			//					substring_start);
			imatch++;
			//do parser a
			{
				int offset1 = 0, retStart1 = 0, retLen1 = retLen;
				int rt1 = pcre_exc_express(re_a, substring_start, retLen1, 0,
						&retStart1, &retLen1);
				if (rt1 == -1) {
					//					printf("\033[1;31m%s\033[0m]\n", "Not match 1");
				}
				else {
					char *substring_start1 = substring_start + retStart1;
					//					printf("[%3d]Match==>url[\033[1;31m%.*s\033[0m]\n", imatch,
					//							retLen1, substring_start1);

					//do parser url
					{
						int offset2 = 0, retStart2 = 0, retLen2 = retLen1;
						int rt2 = pcre_exc_express(re_url, substring_start1,
								retLen2, 0, &retStart2, &retLen2);
						if (rt2 == -1) {
							//							printf("\033[1;31m%s\033[0m]\n", "Not match 2");
						}
						else {
							char *substring_start2 = substring_start1
									+ retStart2 + 5;
							char* str_url = (char*) malloc(retLen2 - 6 + 1);
							memset(str_url, 0, sizeof(str_url));
							sprintf(str_url, "%.*s", retLen2 - 6,
									substring_start2);
							if (strstr(str_url, "jpg") != 0) {
								printf(
										"[%3d]Match==>url[\033[1;31m%s\033[0m]\n",
										imatch, str_url);
							}
						}
					}
				}
			}

			offset = retStart + retLen;
		}
	}
	pcre_free_express(re_url);
	pcre_free_express(re_a);
	pcre_free_express(re_td);
	return 0;

}
